package org.visionlibrary.image.filters.adjustement;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class NormalizeColor extends AbstractFilter {

	@Override
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);
		
		int maxX = src.getWidth();
		int maxY = src.getHeight();

		double[] sums = new double[src.getNumBands()];
		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				for (int ch = 0; ch < src.getNumBands(); ch++) {
					sums[ch] += src.getSample(x, y, ch);
				}
			}
		
		for(int i=0; i < sums.length; i++)
			sums[i] = (3/(maxX * maxY)) * sums[i];
		
		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				double sij = 1;
				for (int ch = 0; ch < src.getNumBands(); ch++) {
					sij += src.getSample(x, y, ch);
				}
				for (int ch = 0; ch < src.getNumBands(); ch++) {
					double xij = src.getSample(x, y, ch) / sij;
					double pixel = xij / sums[ch];
					dest.setSample(x, y, ch, pixel);
				}
			}
		

		return dest;
	}
}
